package fr.webeo.teambuilder.ao;

import java.util.ArrayList;
import java.util.List;

import fr.webeo.teambuilder.bo.Player;
import fr.webeo.teambuilder.bo.Team;

/**
 * The class <strong>TeamForNPlayerModel</strong>.
 * 
 * @author Sébastien Bordes
 * @version $Revision$ $Date$ $Name$
 * 
 * @since fr.webeo.teambuilder 1.0
 */
public class TeamForNPlayerModel extends AbstractModel {

    /** . */
    private MyTeamTableModel teamTableModel;

    /**
     * 
     */
    public TeamForNPlayerModel() {
    }

    public MyTeamTableModel getTeamTableModel() {
        if (this.teamTableModel == null) {
            this.teamTableModel = new MyTeamTableModel(getTeams());
            // Not used yet this.teamTableModel.addTableModelListener(this);
        }
        return this.teamTableModel;
    }

    /**
     * @see fr.webeo.teambuilder.ao.AbstractModel#setTeams(java.util.List)
     */
    @Override
    public void setTeams(List<Team> teams) {
        super.setTeams(teams);
        getTeamTableModel().setTeams(getTeams());
    }

    /**
     * @param teamMateNumberByTeam The teamMateNumberByTeam to set.
     */
    public void setTeamMateNumberByTeam(int teamMateNumberByTeam) {
        getTeamTableModel().setTeamMateNumberByTeam(teamMateNumberByTeam);
        getTeamTableModel().fireTableStructureChanged();
    }

    public void organize(List<Player> temp) {

        List<Team> teams = new ArrayList<Team>();

        String[] teamName = new String[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M" };
        int teamNameIdx = 0;
        Team team = new Team(teamName[teamNameIdx]);
        teams.add(team);

        do {
            int l = (getRandomIndex() % temp.size());
            if (team.getPlayers().size() < getTeamTableModel().getTeamMateNumberByTeam()) {
                team.addPlayer(temp.get(l));
                temp.remove(l);
            } else {
                // Create new team
                teamNameIdx++;
                team = new Team(teamName[teamNameIdx]);
                teams.add(team);
                team.addPlayer(temp.get(l));
                temp.remove(l);
            }
        } while (temp.size() > 0);

        setTeams(teams);

    }

    private int getRandomIndex() {
        long l = Math.round(Math.random() * 10000D);
        return (int) l;
    }
}
